package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ContractVo;
import com.zzyl.vo.ReservationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;


    @Override
    public Long getCancelledReservationCount() {
        LocalDateTime start = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        LocalDateTime end = LocalDateTimeUtil.endOfDay(LocalDateTime.now());
        return reservationMapper.selectCancelledReservationCount(
                UserThreadLocal.getUserId(),
                start,
                end
                );
    }

    @Override
    public List<Map<String, Object>> countByTime(Long time) {
        // 将时间戳转换为LocalDateTime
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        // 获取当天的开始时间和结束时间
        LocalDateTime start = LocalDateTimeUtil.beginOfDay(localDateTime);
        LocalDateTime end = LocalDateTimeUtil.endOfDay(localDateTime);
        return reservationMapper.countByTime(start,end);
    }

    @Override
    public void addReservation(ReservationDto reservationDto) {
        //同一个人，同一个时间段内，只能预约一次


        Reservation reservation = BeanUtil.copyProperties(reservationDto, Reservation.class);
        reservation.setStatus(0);//默认是待报道
        reservationMapper.insertReservation(reservation);
    }

    @Override
    public PageResponse<ReservationVo> selectByPage(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        List<ReservationVo>   page =reservationMapper.selectByPage(status,UserThreadLocal.getUserId());
        return PageResponse.of(page);
    }

    @Override
    public void cancleReservation(Long id) {
        // 查询预约信息
        Reservation reservation = reservationMapper.selectById(id);
        if(reservation == null){
            throw new BaseException(BasicEnum.RESERVATION_FAIL_NOTEXIST);
        }
        if(reservation.getStatus()!=0){
            throw new BaseException(BasicEnum.RESERVATION_CANCEL_FAIL_ILLEGAL_STATUS);
        }
        reservationMapper.cancleReservation(id);
    }
}
